package com.huilan.hgt.controller;


import com.huilan.hgt.entity.Attachment;
import com.huilan.hgt.entity.Catalogue;
import com.huilan.hgt.exception.ExceptionEnum;
import com.huilan.hgt.service.AttachmentService;
import com.huilan.hgt.service.CatalogueService;
import com.huilan.hgt.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author ghy
 * @since 2018-11-02
 */
@Controller
@Configuration
@PropertySource({"classpath:config.properties"})
@RequestMapping("/attachment")
public class AttachmentController {

    @Autowired
    private Environment env;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private CatalogueService catalogueService;

    private static String path;

    @PostConstruct
    public void initParam () {
        path = env.getProperty("file.upload.path");
    }

    /**
     * 上传附件
     */
    @ResponseBody
    @PostMapping(value = "/upload.do")
    public ResponseResult upload(MultipartFile[] files,String code) throws Exception {
        if(StringUtils.isEmpty(code)){
            code = StringUtil.getUUID();
        }
        for (MultipartFile file:files){
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            String date = DateUtil.getStringDateShort();
            String dir = path + File.separator + date + File.separator;

            File newFile = new File(dir+filename);


            File fileParent = newFile.getParentFile();
            if(!fileParent.exists()  && !fileParent.isDirectory()){
                fileParent.mkdirs();
            }
            file.transferTo(newFile);

            Attachment attachment = new Attachment();
            attachment.setAttachmentCode(code)
                    .setAttachmentName(filename)
                    .setAttachmentPath(dir+filename)
                    .setAttachmentSize(StringUtil.convertFileSize(file.getSize()));

            //保存附件
            attachmentService.save(attachment);
        }
        return ResponseResult.success(code);
    }


    /**
     * 附件下载
     */
    @GetMapping(value = "/download/{code}")
    public ResponseEntity<FileSystemResource> download(@PathVariable String code) throws Exception {
        //根据附件编号下载所有附件
        List<Attachment> attachmentList = attachmentService.getAttachmentByCode(code);
        if(attachmentList == null || attachmentList.size()==0){
            throw ExceptionEnum.FILE_NOT_FOUND.getEx();
        }else{
            for(Attachment attachment:attachmentList){
                File file = new File(attachment.getAttachmentPath());
                return export(file,attachment.getAttachmentName());
            }
        }
        return null;
    }


    /**
     * 附件下载，单个文件
     */
    @GetMapping(value = "/download.do")
    public ResponseEntity<FileSystemResource> downloadSingleFile(String id) throws Exception {

        Attachment attachment = attachmentService.getById(id);
        if(attachment!=null){
            File file = new File(attachment.getAttachmentPath());
            return export(file,attachment.getAttachmentName());
        }
        return null;
    }


    public ResponseEntity<FileSystemResource> export(File file,String filename) throws UnsupportedEncodingException {
        if (file == null) {
            return null;
        }
        filename = URLEncoder.encode(filename,"UTF-8");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + filename);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }


    /**
     * 删除附件
     */
    @ResponseBody
    @GetMapping(value = "/delete.do")
    public ResponseResult delete(Integer id)  {
        boolean flag = attachmentService.removeById(id);
        return ResponseResult.success(flag);
    }

    /**
     * 管理文档页面
     */
    @GetMapping("/managingDocument.do")
    public String managingDocument(ModelMap modelMap) {
        //查询所有目录
        List<Catalogue> catalogueList = catalogueService.list(null);
        modelMap.put("catalogueList",catalogueList);
        return "document/file_manager";
    }

    /**
     * 查询所有附件
     */
    @ResponseBody
    @GetMapping("/list.do")
    public PageUtil list(PageUtil<Attachment> page,Integer catalogueId) {

        //查询所有附件
        List<Attachment> list = attachmentService.queryAttachmentList(page,catalogueId);
        page.setRecords(list);
        return page;
    }


    /**
     * 跳转附件上传页面
     */
    @GetMapping("/toUpload.do")
    public String toUpload(ModelMap modelMap) {
        //查询所有目录
        List<Catalogue> catalogueList = catalogueService.list(null);
        modelMap.put("catalogueList",catalogueList);
        return "document/file_upload";
    }


}

